package com.xbongbong.paas.service.team.strategy;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditCoPerVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditLabelVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.team.TeamAfterFormatDTO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PayBalanceUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PayBalanceModel;
import com.xbongbong.saas.model.PayBalanceUserModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shen.yang
 * @version v1.0
 * @Description 预付款团队策略类
 * @date 2022/3/22 11:21
 * @since v1.0
 */
@Service
@Slf4j
public class PayBalanceTeamStrategy extends AbstractTeamStrategy implements TeamStrategy {
    @Resource
    private PayBalanceUserModel payBalanceUserModel;
    @Resource
    private PayBalanceModel payBalanceModel;
    @Resource
    private FormDataHelp formDataHelp;


    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.PREPAY_BALANCE.getCode());
    }

    @Override
    public TeamAfterVerifyDTO verify(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        return super.verifyTeam(teamVerifyDTO);
    }

    @Override
    public TeamAfterVerifyDTO specialVerify(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        return teamAfterVerifyDTO;
    }

    @Override
    public void save(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        TeamAfterFormatDTO teamAfterFormatDTO = formatTeam(teamAfterVerifyDTO);
        List<Long> dataId = teamAfterVerifyDTO.getDataId();
        Integer businessType = teamAfterVerifyDTO.getBusinessType();

        LinkedHashMap<String, Integer> esWait = judgeTeamEsWait(teamAfterFormatDTO);

        for (Iterator<Map.Entry<String, Integer>> iterator = esWait.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Integer> entry = iterator.next();
            boolean hasNext = iterator.hasNext();
            switch (entry.getKey()) {
                case TeamMembersConstant.ADD_USER:
                    List<UserTeamEntity> addUserTeamList = teamAfterFormatDTO.getAddUserTeamList();
                    if (CollectionsUtil.isNotEmpty(addUserTeamList)) {
                        List<PayBalanceUserEntity> payBalanceUserEntityList = new ArrayList<>();
                        try {
                            BeanUtil.copyPropertiesList(addUserTeamList, payBalanceUserEntityList, PayBalanceUserEntity.class, false);
                        } catch (Exception e) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                        }

                        //List<PaasFormDataEntityExt> byDataIdList = formDataHelp.getByDataIdList(dataId, businessType, SaasMarkEnum.SAAS.getCode(), teamAfterVerifyDTO.getFormId(), corpid);
                        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        param.put(StringConstant.CORPID, corpid);
                        param.put(StringConstant.IDIN, dataId);
                        param.put(StringConstant.FORM_ID, teamAfterVerifyDTO.getFormId());
                        List<PayBalanceEntity> payBalanceEntityList = payBalanceModel.findEntitys(param);
                        //获取dataId -> supplierId 映射关系
                        Map<Long,Long> supplierResult = payBalanceEntityList.stream().collect(Collectors.toMap(PayBalanceEntity::getId, PayBalanceEntity::getSupplierId));

                        payBalanceUserEntityList.forEach(v -> {
                            v.setSupplierId(supplierResult.get(v.getDataId()));
                        });

                        if (hasNext) {
                            payBalanceUserModel.insertBatch(payBalanceUserEntityList, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        } else {
                            payBalanceUserModel.insertBatch(payBalanceUserEntityList, WriteRequest.RefreshPolicy.NONE);
                        }
                    }
                    break;
                case TeamMembersConstant.DEL_USER:
                    List<UserTeamEntity> delUserTeamList = teamAfterFormatDTO.getDelUserTeamList();
                    if (CollectionsUtil.isNotEmpty(delUserTeamList)) {
                        List<Long> idIn = delUserTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            payBalanceUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            payBalanceUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_MAIN_USER:
                    List<UserTeamEntity> updateUserToMainTeamList = teamAfterFormatDTO.getUpdateUserToMainTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToMainTeamList)) {
                        List<Long> idIn = updateUserToMainTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            payBalanceUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            payBalanceUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_CO_USER:
                    List<UserTeamEntity> updateUserToCoTeamList = teamAfterFormatDTO.getUpdateUserToCoTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToCoTeamList)) {
                        List<Long> idIn = updateUserToCoTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            payBalanceUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            payBalanceUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.UPDATE_USER:
                    break;
                default:
            }
        }




    }

    @Override
    public void afterSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        List<Long> dataId = teamAfterVerifyDTO.getDataId();
        long now = DateTimeUtil.getInt();
        //更新时间
        List<UpdateDataEntity> updateDataEntities = new ArrayList<>();
        dataId.forEach(v -> {
            UpdateDataEntity updateDataEntity = new UpdateDataEntity();
            updateDataEntity.setUpdateTime(now);
            updateDataEntity.setId(v);
            updateDataEntity.setCorpid(corpid);
            updateDataEntities.add(updateDataEntity);
        });
        payBalanceModel.updateBatch(updateDataEntities,corpid, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void log(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        super.log(teamAfterVerifyDTO);
    }

    @Override
    public TeamDetailEditCoPerVO editCoPermission(TeamDetailUpdateDTO teamDetailUpdateDTO) throws XbbException {
        return null;
    }

    @Override
    public TeamDetailEditLabelVO editLabel(TeamDetailEditLabelDTO teamDetailEditLabelDTO) throws XbbException {
        return null;
    }
}
